--全服争霸
--#include "data\config\activityconfig\DailyActivity\ServerPKConfig.lua" once


function ServerPKPrepare()
	local sysVar = System.getDyanmicVar()
	sysVar.ServerPKPrepare = 1
	sysVar.ServerPKPrepareTime = System.getCurrMiniTime() + ServerPKConfig.PrepareTime
	gRankMgr_Clear(RANK_DEFINE_SERVERPK)
	local msg = Lang.ScriptTips.ServerPK011
	System.broadcastTipmsg(msg, ttScreenCenter + ttChatWindow)
end

function ServerPKStart()
	local sysVar = System.getDyanmicVar()
	sysVar.ServerPKPrepare = nil
	sysVar.ServerPKStartTime = System.getCurrMiniTime()
	local nSceneId = ServerPKConfig.PreparePos[1]
	local playerList = LuaHelp.getSceneActorListById(nSceneId) or {}
	for k,v in pairs(playerList)do
		if v then
			CloseActivityRightPanel(v)
			Actor.enterScene(v,unpack(ServerPKConfig.ActivityPos))	
			Actor.setPkMode(v, fpPk)
			ServerPKRightPanel(v)
		end
	end
	Actor.unregScriptCallback( System.getGlobalNpc(), "ServerPKTimer")
	Actor.unregScriptCallback( System.getGlobalNpc(), "ServerPKSceneMsgTimer")	
	Actor.regScriptTimer(System.getGlobalNpc(), 0, 0, ServerPKConfig.AutoPointTimer * 1000, -1, "ServerPKTimer")
	Actor.regScriptTimer(System.getGlobalNpc(), 0, 0, ServerPKConfig.SceneMsgTimer * 1000, -1, "ServerPKSceneMsgTimer")
	local msg = Lang.ScriptTips.ServerPK012
	System.broadcastTipmsg(msg, ttScreenCenter + ttChatWindow)
end

function ServerPKEnd()
	Actor.unregScriptCallback( System.getGlobalNpc(), "ServerPKTimer")
	Actor.unregScriptCallback( System.getGlobalNpc(), "ServerPKSceneMsgTimer")	
	local nSceneId = ServerPKConfig.ActivityPos[1]
	local playerList = LuaHelp.getSceneActorListById(nSceneId) or {}
	for k,v in pairs(playerList)do
		if v then
			CloseActivityRightPanel(v)
			Actor.enterScene(v,unpack(ServerPKConfig.ExitPos))	
			Actor.setPkMode(v, fpPeaceful)
			SendActivityLog(v, ACTIVITY_DEFINE_SERVERPK, ActLogStatus_Complete)
		end
	end
	ServerPKAward()
	SendPKEndMsg()
end

function SendPKEndMsg()
	local rankName = RankList[RANK_DEFINE_SERVERPK].strName
	local ranking = Ranking.getRanking( rankName )
	if  ranking == nil then
		return
	end
	local rankItem = Ranking.getItemFromIndex(ranking, 0)
	local msg = Lang.ScriptTips.ServerPK010
	if rankItem then
		local nPoint =  Ranking.getPoint(rankItem)
		if nPoint >= ServerPKConfig.RankLimit then
			local name = Ranking.getSub(rankItem,0)
			msg = string.format(Lang.ScriptTips.ServerPK009, name)
		end
	end
	System.broadcastTipmsg(msg, ttScreenCenter + ttChatWindow)
end

function ServerPKEnterPrepareScene(sysarg)
	Actor.enterScene(sysarg,unpack(ServerPKConfig.PreparePos))
	Actor.setPkMode(sysarg, fpPeaceful)
	local sVar = Actor.getStaticVar(sysarg)
	sVar.ServerPKDie = nil 
	ServerPKRightPanel(sysarg)
end

function ServerPKRightPanel(sysarg)
	local sysVar = System.getDyanmicVar()
	local PrepareTime  = (sysVar.ServerPKPrepareTime or 0) - System.getCurrMiniTime()
	local EndTime = (sysVar.ServerPKStartTime or 0)  + ServerPKConfig.Time - System.getCurrMiniTime() 
	local panelInfo = {}
	panelInfo.sts = 1
	panelInfo.title = Lang.ScriptTips.ServerPKPanel001
	if EndTime >= 0 then
		panelInfo.timeTitle = Lang.ScriptTips.ServerPKPanel002
		panelInfo.restTime =  EndTime
	else
		panelInfo.timeTitle = Lang.ScriptTips.ServerPKPanel007
		panelInfo.restTime =  PrepareTime
	end
	panelInfo.contentTitle = ""

	local myScore 	= 0
	local myIdx 	= 0
	local rankName = RankList[RANK_DEFINE_SERVERPK].strName
	local ranking = Ranking.getRanking( rankName )
	local firstName = "暂无"
	local firstScore = "0"
	if ranking then
		local rankLimit = ServerPKConfig.RankLimit
		local myId = Actor.getActorId(sysarg)
		local item = Ranking.getItemPtrFromId(ranking, myId)
		if item then
			myScore = Ranking.getPoint(item) or 0
			if myScore < rankLimit then
				myIdx = 0
			else
				myIdx = Ranking.getIndexFromPtr(item) + 1
			end
		end
		local firstItem = Ranking.getItemFromIndex(ranking,0)
		if firstItem then
			firstName =  Ranking.getSub(firstItem,0)
			firstScore = Ranking.getPoint(firstItem)
		end
	end
		
	panelInfo.contents = {}
	panelInfo.contents[1] = Lang.ScriptTips.ServerPKPanel003..myScore
	panelInfo.contents[2] = Lang.ScriptTips.ServerPKPanel004..myIdx
	panelInfo.contents[3] = Lang.ScriptTips.ServerPKPanel005..firstName
	panelInfo.contents[4] = Lang.ScriptTips.ServerPKPanel006..firstScore
	
	panelInfo.awardTitle = ""
	panelInfo.awards = {}
	panelInfo.buttons = {1}

	local panelType = 2
	local activityId = enRightPanelActivity_ServerPK
	OpenActivityRightPanel( sysarg, panelType, activityId, panelInfo)
end

function ChangeServerPKRightPanelAll()
	local playerList = LuaHelp.getSceneActorListById(ServerPKConfig.ActivityPos[1]) or {}
	for i,v in ipairs(playerList) do
	 	ChangeServerPKRightPanel(v)
	end
end

function ChangeServerPKRightPanel(sysarg)
	local panelInfo = {}
	panelInfo.sts = 1
	panelInfo.contentTitle = ""

	local myScore 	= 0
	local myIdx 	= 0
	local rankName = RankList[RANK_DEFINE_SERVERPK].strName
	local ranking = Ranking.getRanking( rankName )
	local firstName = "暂无"
	local firstScore = "0"
	if ranking then
		local rankLimit =  ServerPKConfig.RankLimit
		local myId = Actor.getActorId(sysarg)
		local item = Ranking.getItemPtrFromId(ranking, myId)
		if item then
			myScore = Ranking.getPoint(item) or 0
			if myScore < rankLimit then
				myIdx = 0
			else
				myIdx = Ranking.getIndexFromPtr(item) + 1
			end
		end
		local firstItem = Ranking.getItemFromIndex(ranking,0)
		if firstItem then
			firstName =  Ranking.getSub(firstItem,0)
			firstScore = Ranking.getPoint(firstItem)
		end
	end
		
	panelInfo.contents = {}
	panelInfo.contents[1] = Lang.ScriptTips.ServerPKPanel003..myScore
	panelInfo.contents[2] = Lang.ScriptTips.ServerPKPanel004..myIdx
	panelInfo.contents[3] = Lang.ScriptTips.ServerPKPanel005..firstName
	panelInfo.contents[4] = Lang.ScriptTips.ServerPKPanel006..firstScore
	
	panelInfo.buttons = {1}
	ChangeActivityRightPanel( sysarg, panelInfo )
end

function  ServerPKTimer()
	local nSceneId =  ServerPKConfig.ActivityPos[1]
	local playerListAll = LuaHelp.getSceneActorListById(nSceneId) or {}
	if #playerListAll == 0  then return end
	local playerList = {}
	for k,v in pairs(playerListAll) do
		if  Actor.isDeath(v) == false  then
			table.insert(playerList,v)
		end	
	end
	if  #playerList == 0 then return end
	for k,sysarg in pairs(playerList)do
		if sysarg then 
			if Actor.hasMapAreaAttri(sysarg, aaPaoDianAddExpArea) then
				local nActorId = Actor.getIntProperty(sysarg, PROP_ENTITY_ID)
				gRankMgr_AddValue(nActorId, RANK_DEFINE_SERVERPK, ServerPKConfig.AutoPoint)
				Actor.sendTipmsg(sysarg, string.format(Lang.ScriptTips.ServerPK004, ServerPKConfig.AutoPoint, ttTipmsgWindow + ttChatWindow))
			end
			GiveCommonAward(sysarg, ServerPKConfig.AutoExp , LogIds.ServerPKLogId, Lang.LogTips.ServerPK)
		end
	end
	ChangeServerPKRightPanelAll()
end

function ServerPKSceneMsgTimer()
	local rankName = RankList[RANK_DEFINE_SERVERPK].strName
	local ranking = Ranking.getRanking( rankName )
	if  ranking == nil then
		return
	end
	local rankItem = Ranking.getItemFromIndex(ranking, 0)
	if rankItem then
		local nPoint =  Ranking.getPoint(rankItem)
		if nPoint >= ServerPKConfig.RankLimit then
			local nSceneId = ServerPKConfig.ActivityPos[1]
			local hScene =  Fuben.getSceneHandleById(nSceneId)
			local nActorId = Ranking.getId(rankItem)
			local pActor = Actor.getActorById(nActorId)
			local name =  Ranking.getSub(rankItem,0)
			if hScene and pActor and IsInServerPK(pActor) then
				local x,y = Actor.getEntityPosition(pActor,0,0)
				local msg = string.format(Lang.ScriptTips.ServerPK008, Actor.getName(pActor), x, y)
				Fuben.sendMsgToScene(hScene, msg, ttScreenCenter)
			end	
		end
	end
end

function IsInServerPK(sysarg)
	local  nSceneId =  Actor.getSceneId(sysarg)
	if nSceneId ==  ServerPKConfig.ActivityPos[1] then
		return true
	end
	return false
end

function ServerPKActorDeath(sysarg, killerPtr)
	if  sysarg == nil or killerPtr == nil then
		return
	end
	if IsInServerPK(sysarg) == false then
		return
	end
	if Actor.isMonster(killerPtr) then
		return
	end
	local dieActorId = Actor.getIntProperty( sysarg, PROP_ENTITY_ID )
	local dieCircle =  Actor.getIntProperty( sysarg, PROP_ACTOR_CIRCLE)
	local nActorId = Actor.getIntProperty(killerPtr, PROP_ENTITY_ID ) 
	local dieScore = gRankMgr_GetValue(dieActorId, RANK_DEFINE_SERVERPK) or 0
	local AddScore =  (ServerPKConfig.CirclePoint[dieCircle + 1] or 0)  +  math.ceil(dieScore * (ServerPKConfig.KilledPointRate))
	gRankMgr_AddValue(nActorId,  RANK_DEFINE_SERVERPK, AddScore)
	gRankMgr_SetRank(dieActorId, RANK_DEFINE_SERVERPK, math.ceil(dieScore * (1 - ServerPKConfig.KilledPointRate)) )
	ChangeServerPKRightPanelAll()
end

function  ServerPKAward()
	local rankName = RankList[RANK_DEFINE_SERVERPK].strName
	local ranking = Ranking.getRanking( rankName )
	if (ranking == nil) then
		return
	end
	local cfg = ServerPKConfig
	local num = cfg.Awards[#cfg.Awards].condition[2]
	local itemNum = Ranking.getRankItemCount(ranking)
	if itemNum > num then
		itemNum = num
	end	
	local title = Lang.ScriptTips.ServerPK006				
	local rankLimit = cfg.RankLimit
	for idx=1,itemNum do
		local rankItem = Ranking.getItemFromIndex(ranking, idx-1)
		if rankItem then
			local actorId  = Ranking.getId(rankItem)
			local sysarg = Actor.getActorById(tonumber(actorId))
			local myScore = Ranking.getPoint(rankItem) or 0
			local content = string.format(Lang.ScriptTips.ServerPK007,idx)
			if  rankLimit <= myScore then
				local ItemAwards = ServerPKGetAward(idx)
				Awards.GiveToMailById(actorId, ItemAwards, title, content, LogIds.ServerPKLogId, Lang.LogTips.ServerPK)
			else
				break
			end
		end
	end	
end

function ServerPKGetAward(idx)
	local awards = {}
	for k,v in ipairs(ServerPKConfig.Awards)do
		if  v.condition[1] <= idx and idx <= v.condition[2]  then
			awards = v.awards
			break
		end
	end
	return awards
end

function SendServerPKRank(sysarg)
	local rankName = RankList[RANK_DEFINE_SERVERPK].strName
	local rankingPtr = Ranking.getRanking(rankName)
	if rankingPtr == nil then
		return
	end
	local cfg = ServerPKConfig
	local num = cfg.RankCount
	local itemNum = Ranking.getRankItemCount(rankingPtr)
	if num < Ranking.getRankItemCount(rankingPtr) then
		itemNum = num
	end
	local pack = DataPack.allocPacket(sysarg, LogicCmd.activitySys.sysId, LogicCmd.activitySys.sub.sSendServerPKRank)
	if pack == nil then
		return
	end
	local rankLimit = cfg.RankLimit
	local sendNum = true
	local sendDataNum 
	for idx=itemNum,1, -1 do
		local rankItem = Ranking.getItemFromIndex(rankingPtr, idx-1)
		if rankItem then
			local value = Ranking.getPoint(rankItem)
			if value >= rankLimit then
				if sendNum then
					if idx > num then
						sendDataNum = num
					else
						sendDataNum = idx
					end
					DataPack.writeWord(pack, sendDataNum)
					sendNum = false
				end
				if idx <= sendDataNum then
					local name = Ranking.getSub(rankItem, 0)
					DataPack.writeString(pack, name)			
					DataPack.writeUInt(pack, value)
					DataPack.writeByte(pack, tonumber(Ranking.getSub(rankItem, 1)) )
					DataPack.writeWord(pack, tonumber(Ranking.getSub(rankItem, 2)) )
				end
			end
		end
	end
	if sendNum then
		DataPack.writeWord(pack, 0)
	end

    DataPack.writeByte(pack, num)
	for i = 1, num do 
		local awards  = ServerPKGetAward(i) or {}
		DataPack.writeByte(pack, #awards)
		for k, v in ipairs(awards) do
			DataPack.writeByte(pack, v.type or 0)
			DataPack.writeInt(pack, v.id or 0)
			DataPack.writeInt(pack, v.count or 0)
			DataPack.writeByte(pack, v.quality or 0)
			DataPack.writeByte(pack, v.bind or 0)
		end
	end
	DataPack.flush(pack)
end


function OnServerPKRelive(sysarg, reliveType)
	local sVar = Actor.getStaticVar(sysarg)
	sVar.ServerPKDie = (sVar.ServerPKDie or 0) + 1
	if sVar.ServerPKDie >  ServerPKConfig.GameOverTime then
		Actor.sendTipmsg(sysarg, string.format(Lang.ScriptTips.ServerPK005, ServerPKConfig.GameOverTime), ttTipmsgWindow + ttChatWindow)
		CloseActivityRightPanel(sysarg)
		Actor.enterScene(sysarg,unpack(ServerPKConfig.ExitPos))
	else
		local hp = Actor.getUIntProperty(sysarg, PROP_CREATURE_MAXHP)
		local mp = Actor.getUIntProperty(sysarg, PROP_CREATURE_MAXMP)
		Actor.setUIntProperty(sysarg,PROP_CREATURE_HP,hp)
		Actor.setUIntProperty(sysarg,PROP_CREATURE_MP,mp)
		Actor.enterScene(sysarg,unpack(ServerPKConfig.ActivityPos))	
		ServerPKRightPanel(sysarg)
	end
end

SceneReliveDispatcher.register(ServerPKConfig.ActivityPos[1], OnServerPKRelive)